package com.nintendo.bubblechat.controller;

import com.nintendo.bubblechat.config.MinioConfig;
import com.nintendo.bubblechat.entity.pojo.FriendsRequest;
import com.nintendo.bubblechat.entity.dto.GroupChatDTO;
import com.nintendo.bubblechat.entity.pojo.GroupChat;
import com.nintendo.bubblechat.entity.vo.UsersVo;
import com.nintendo.bubblechat.grace.result.GraceJsonRequest;
import com.nintendo.bubblechat.service.FriendRequestService;
import com.nintendo.bubblechat.service.UsersService;
import com.nintendo.bubblechat.utils.MinioUtils;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.List;

@RestController
@RequestMapping("/friend")
@Slf4j
public class FriendController {
    @Autowired
    private UsersService userService;
    @Autowired
    private FriendRequestService friendRequestService;
    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private MinioUtils minioUtils;
    @PostMapping("/search")
    public GraceJsonRequest searchFriend(@RequestParam("mobile") String mobile) {
        UsersVo usersVo = userService.searchFriend(mobile);
        return GraceJsonRequest.ok(usersVo);
    }

    @PostMapping("/sendRequest")
    public GraceJsonRequest sendSendRequest(@RequestBody FriendsRequest friendRequest) {
        friendRequestService.saveRequest(friendRequest);
        return GraceJsonRequest.ok();
    }

    @PostMapping("/findRequest")
    public GraceJsonRequest findRequest(@RequestParam("acceptUserId") String acceptUserId) {
        List<UsersVo> findRequest = friendRequestService.findRequest(acceptUserId);
        return GraceJsonRequest.ok(findRequest);
    }

    /**
     * 忽略好友请求
     *
     * @param request
     * @return
     */
    @PostMapping("/ignore")
    public GraceJsonRequest ignore(@RequestBody FriendsRequest request) {
        friendRequestService.ignore(request);
        return GraceJsonRequest.ok();
    }

    /**
     * 通过好友请求
     *
     * @param request
     * @return
     */
    @PostMapping("/pass")
    public GraceJsonRequest pass(@RequestBody FriendsRequest request) {
        friendRequestService.pass(request);
        return GraceJsonRequest.ok();
    }

    @PostMapping("/findMyFriend")
    public GraceJsonRequest findMyFriend(@RequestParam("myUserId") String myUserId) {
        List<UsersVo> users = friendRequestService.findMyFriends(myUserId);
        return GraceJsonRequest.ok(users);
    }

    /**
     * 根据朋友id查询朋友信息
     *
     * @param friendUserId
     * @return
     */
    @PostMapping("/findFriendProfile")
    public GraceJsonRequest findFriendProfile(@RequestParam("friendUserId") String friendUserId) {
        UsersVo usersVo = userService.findFriendProfile(friendUserId);
        return GraceJsonRequest.ok(usersVo);
    }

    /**
     * 创建群聊
     */
    @PostMapping("/createGroup")
    public GraceJsonRequest createGroup(@RequestBody GroupChatDTO groupChatDTO) {
        friendRequestService.createGroup(groupChatDTO);
        return GraceJsonRequest.ok();
    }
    /**
     * 查询我的群聊和我加入的群聊
     */
    @PostMapping("/findMyGroupAndIn")
    public GraceJsonRequest findMyGroupAndIn(@RequestParam("myId") String myId) {
        List<GroupChat> groupChatList =  friendRequestService.findMyGroupAndIn(myId);
        return GraceJsonRequest.ok(groupChatList);
    }
    /**
     * 获取群组成员
     */
    @PostMapping("/getGroupMembers")
    public GraceJsonRequest getGroupMembers(@RequestParam("groupId")String groupId){
        List<UsersVo> users = friendRequestService.getGroupMembers(groupId);
        return GraceJsonRequest.ok();
    }
    /**
     *生成九宫格图片
     */

    /**
     * 接收最多9张图片的URL地址，生成九宫格图片并上传到 MinIO 服务器
     *
     * @param imageUrls 图片URL列表
     * @return MinIO 中新生成图片的访问地址
     * @throws IOException 如果图片加载失败或文件写入失败
     */
    @PostMapping("/create-grid")
    public GraceJsonRequest createImageGrid(@RequestBody List<String> imageUrls) throws Exception {
        // 确保图片数量不超过9张
        if (imageUrls.size() > 9 || imageUrls.isEmpty()) {
            throw new IllegalArgumentException("图片数量必须在1到9之间");
        }

        // 定义每个小图的尺寸（可以根据需要调整）
        int cellWidth = 200;
        int cellHeight = 200;

        // 计算九宫格的行数和列数
        int rows = (int) Math.ceil(imageUrls.size() / 3.0);
        int cols = Math.min(imageUrls.size(), 3);

        // 创建一个新的空白图片作为画布
        BufferedImage gridImage = new BufferedImage(
                cols * cellWidth, rows * cellHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = gridImage.createGraphics();
        g2d.setColor(Color.WHITE); // 设置背景色为白色
        g2d.fillRect(0, 0, cols * cellWidth, rows * cellHeight);

        // 遍历图片URL列表，将每张图片绘制到九宫格中
        for (int i = 0; i < imageUrls.size(); i++) {
            String imageUrl = imageUrls.get(i);
            BufferedImage img = ImageIO.read(new URL(imageUrl));

            // 缩放图片以适应单元格大小
            img = resizeImage(img, cellWidth, cellHeight);

            // 计算图片的位置
            int row = i / 3;
            int col = i % 3;
            int x = col * cellWidth;
            int y = row * cellHeight;

            // 将图片绘制到画布上
            g2d.drawImage(img, x, y, null);
        }
        g2d.dispose();

        // 将生成的图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(gridImage, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();

        // 调用 MinIO 上传方法
        ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
        MultipartFile multipartFile = new MockMultipartFile("grid.jpg", "grid.jpg", "image/jpeg", inputStream);
        String uploadedPath = minioUtils.upload(multipartFile);
        uploadedPath ="http://"+minioConfig.getEndpoint()+":"+minioConfig.getPort()+"/"+uploadedPath;
        return GraceJsonRequest.ok(uploadedPath);
    }

    /**
     * 调整图片大小
     *
     * @param originalImage 原始图片
     * @param width         目标宽度
     * @param height        目标高度
     * @return 调整后的图片
     */
    private BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }
    /**
     * 根据群聊Id获取群组信息
     */
    @PostMapping("/getGroupInfoByGroupId")
    public GraceJsonRequest getGroupInfo(@RequestParam("groupId")String groupId){
        System.out.println("groupId =====>"+groupId);
        List<GroupChat> groupChats = friendRequestService.getGroupInfo(groupId);
        return GraceJsonRequest.ok(groupChats);
    }
}
